<template>
    <div class="chat-warp" ref="chatWarp">
        <div class="goods-warp" v-if="fromGoods" ref="goodsWarp">
            <img v-if="goodsInfo" :src="goodsInfo.logo" alt="" class="left">
            <div class="center">
                <div v-if="goodsInfo" class="name-box">{{'¥ '+goodsInfo.discountPrice}}</div>
                <div v-if="goodsInfo" class="section-line">
                    {{goodsInfo.name}}
                </div>
                <div class="supplement">
                    <span>交易前聊一聊</span>
                </div>
            </div>
        </div>
        <div class="chatBox-kuang" ref="chatBoxkuang" style="display: block;">
          <div class="chatBox-content" ref='chatBoxScroll'>
            <div class="chatBox-content-demo" ref='chatBoxDemo'>
              
              <div class="clearfloat" v-for="(item,index) in chatList" :key="index">
                <div class="author-name">
                  <small class="chat-date">{{item.date}}</small> 
                </div> 
                <div :class="[item.from==phone?'right':'left']"> 
                  <div class="chat-message">{{item.data}}<br></div> 
                  <div class="chat-avatars">
                    <img :src="item.headImg" alt="头像">
                  </div> 
                </div> 
              </div>
            </div>

            <div class="chatBox-send" ref="chatBoxSend">
                <input type="text" placeholder="想对Ta说点什么？" v-model.trim="inputText" name="inputText" ref="inputText" @keydown.enter="sendPrivateText(inputText)">
                <div @click="sendPrivateText(inputText)">
                    发送
                </div>
            </div>
          </div>
        </div>
        <!-- <div class="scroll-box">
            <div class="group" v-infinite-scroll="loadMore"
                 infinite-scroll-disabled="busy"
                infinite-scroll-distance="10">
                <div class="cell-box  flex" v-for="(item,index) in messageList" :key="index">
                    <div class="news-box flex">
                        <img :src="item.headimgurl" alt="" class="left">
                        <div class="center">
                            <div class="name-box">{{item.nickname}}</div>
                            <div class="section-line">
                                {{item.city}}
                            </div>
                            <div class="supplement">
                                <span>{{item.fansCount}}位粉丝</span>
                            </div>
                        </div>
                    </div>
                </div>
             <load-more :tip="loadingText" :show-loading="loading"></load-more>
           </div>
        </div> -->
        <!-- <div class="bom-tip">请不要相信任何人发送的二维码链接,请勿私下交易谨防被骗</div> -->
    </div>
</template>

<script>
    import {Cell,Group,CellBox,Card,LoadMore} from "vux";
    import { mapState,mapGetters,mapMutations } from "vuex";

 import axios from '@/api/request'
    export default {
        data() {
            return {
                idx:0,
                loadingText:"正在加载",
                loading:true,
                busy:false,
                pageNumber:0,
                now:"tb_user_entity",
                messageList: [],
                inputText: '',
                secGoodsId: '',
                goodsInfo: null,
                chatList: [
                  
                ],
                fromGoods: null,
                userInfo: null,
                serviceInfo: null,
                imgAndNicknameInfo: {},
                goodsPhone:'',
            }
        },
        components: {
            Cell,
            Group,
            CellBox,
            LoadMore
        },
        computed:{
            ...mapState({ 
                imIsLogin: state => state.IMISLOGIN,
            }),
            ...mapGetters({
              openId: 'doneOpenId',
              userId: 'doneUserId',
              phone: 'donePhone',
              password: 'donePassword',
            }),
        },
        created(){
            this.secGoodsId = this.$route.query.secGoodsId
            this.goodsId = this.$route.query.goodsId
            this.fromGoods = this.$route.query.fromGoods  //为true就是从商品来的
            if(this.secGoodsId){  //二手店铺进来的
                this.getSecGoodsInfo(this.secGoodsId)
                this.type = 1
            }
            if(this.goodsId){   //普通店铺进来的
                console.log(this.goodsId)
                this.getGoodsInfo(this.goodsId)
                this.type = 2
            }
            if(!this.fromGoods){
                this.goodsPhone = this.$route.query.servicePhone
                this.type = this.$route.query.type
                this.getUserShopImg()
                this.getChatList()
            }
            console.log(this.imIsLogin)
            if(!this.imIsLogin){  //判断是否登录
                this.IMlogin()   
            }else{
                
            }
        },
        mounted(){
            if(!this.fromGoods){ //从列表进来的,不显示商品
                let chatWarp = this.$refs.chatWarp.offsetHeight
                this.$refs.chatWarp.style.paddingTop = 0 + 'px'
                this.$refs.chatBoxkuang.style.height = chatWarp +'px'
                this.$refs.chatBoxkuang.style.top = 0 +'px'
            }else{     //商品进来的

            }
            var self = this;
            self.$imConn.listen({
                onOnline: function() {  
                    console.log('本机网络连接成功')
                }, 
                onOpened: function (message) { //登录成功
                    console.log('登录成功', message)
                    self.SET_IMLOGINSTATUS(true)
                },
                onClosed: function (message) { //连接关闭
                    console.log('登录状态已关闭', message)
                    self.SET_IMLOGINSTATUS(false)
                },
                onRoster: function(message) { //处理好友申请
                    console.log(message);
                }, 
                onTextMessage: function ( message ) {
                    console.log(message);
                    console.log("有新的消息");
                    var date = new Date().format("yyyy-MM-dd hh:mm:ss");
                    let chatData = {
                        id: message.id,
                        date: date,
                        data: message.data,
                        headImg: self.imgAndNicknameInfo.toImgUrl,
                        from: message.from,
                        to: message.to,
                    }
                    self.chatList.push(chatData)
                    self.$nextTick(()=> {
                        let aa = self.$refs.chatBoxDemo.offsetHeight
                        console.log(aa)
                        self.$refs.chatBoxScroll.scrollTop = aa;
                    })
                },
                onPresence: function ( message ) {
                    // 这里需要弹出面板标识有人要添加您为好友
                    console.log(message)
                    if(message.type == 'subscribe') {
                        self.privateUser = message.from;
                        self.privateUserPanel = true;
                    }
                }
            });
        },
        methods: {
            ...mapMutations(['SET_IMLOGINSTATUS']),
            getGoodsInfo(){   //获取一手商品信息  
                var self=this
                axios('/device/product/get/'+this.goodsId,'post',{}).then(res=>{
                    if(res.data.code==1000){
                        // console.log(res)
                        this.goodsInfo = res.data.data
                        this.goodsPhone = res.data.data.createUser
                        this.getUserShopImg()
                        this.getChatList()
                    }
                })
            },
            getSecGoodsInfo(id){   //获取二手商品信息
                var self=this 
                axios('/device/productSecond/getById','post',{id: id}).then(res=>{
                    if(res.data.code==1000){
                        // console.log(res)
                        this.goodsInfo = res.data.data.product
                        this.avatar = res.data.data.headImg
                        this.goodsPhone = res.data.data.phone
                        this.getUserShopImg()
                        this.getChatList()
                    }
                })
            },
            getUserShopImg() {   //查自己的和别人的头像和nickname
                let data = {
                    type: this.type,
                    from: this.phone,         //发消息的人
                    to: this.goodsPhone,      //接受消息的人
                }
                axios('/device/userEntity/getUserShopImg','post',data).then(res=>{
                    if(res.data.code==1000){
                        console.log('自己的')
                        console.log(res)
                        this.imgAndNicknameInfo = res.data.data
                    }else if(res.data.code==1011){
                        console.log("参数错误")
                    }
                })
            },
            getChatList(){   //获取聊天记录
               // var data={
               //   pageNumber: this.pageNumber,
               //   pageSize:10,
               //   param:{
               //     userName : this.phone,
               //   }
               // }
               let data = {
                    userName: this.phone,  
                    serviceName: this.goodsPhone,
                }
                axios('/device/userEase/updateQueryList','post',data).then(res=>{
                    if(res.data.code==1000){
                        // console.log(res) 
                        this.content2chatList(res.data.data)
                    }
                })
            },
            sendPrivateText(msgText) {    //发消息
                // if(!this.imIsLogin){  //判断是否登录
                //     this.IMlogin()   
                // }else{
                    
                // }
                if(msgText){
                    let self = this;
                    var date = new Date().format("yyyy-MM-dd hh:mm:ss");  
                    var id = this.$imConn.getUniqueId();         // 生成本地消息id
                    var msg = this.$WebIM.message('txt', id);    // 创建文本消息

                    let chatData = {
                        id: id,
                        date: date,
                        data: msgText,
                        headImg: this.imgAndNicknameInfo.fromImgUrl,
                        from: this.phone,
                        to: this.goodsPhone,
                    }
                    console.log(chatData)
                    self.chatList.push(chatData)
                    self.$nextTick(()=> {
                        let aa = self.$refs.chatBoxDemo.offsetHeight
                        console.log(aa)
                        self.$refs.chatBoxScroll.scrollTop = aa;
                    })
                    msg.set({
                        msg: msgText,                            // 消息内容
                        to: this.goodsPhone,                          // 接收消息对象（用户id）
                        roomType: false,
                        success: function (id, serverMsgId) {
                            console.log('发送成功')
                            //发送后清空输入框
                            self.inputText = ""
                            var dataMessage = {
                                userName: self.phone,   //自己的用户名(手机号)
                                password: '123456',       //密码
                                serviceName: self.goodsPhone,  //接收人
                                content: msgText,
                                userProduct: "user",
                                productId: self.goodsInfo?self.goodsInfo.id:0,
                                productName: self.goodsInfo?self.goodsInfo.name:0,
                                readUser: "wd",             //已读未读
                                url: "www",                 //商品链接
                                img: self.goodsInfo?self.goodsInfo.logo:0,   //商品图像 
                                type: self.type, 
                                userImg: self.imgAndNicknameInfo.fromImgUrl,
                                oppositeImg: self.imgAndNicknameInfo.toImgUrl,     //收消息人图像
                                userNick: self.imgAndNicknameInfo.fromName, //发消息人要显示给接收方的名字   后加的
                                serviceNick: self.imgAndNicknameInfo.toName,     //接收方要显示给发消息人的名字    后加的 
                            };
                            self.addMessage(dataMessage,"addChatMessage")
                            // console.log('发送成功')
                        },
                        fail: function(e){
                            console.log("Send private text error");
                        }
                    });
                    msg.body.chatType = 'singleChat';
                    this.$imConn.send(msg.body);
                }else{
                    this.$vux.toast.text('发送内容不能为空', 'middle')
                }
            },
            addMessage(dataMessage,method){  //访问后台接口，添加或更新msg
                console.log('即将发送')
                axios('/device/userEase/'+method,'post',dataMessage).then(res=>{
                    if(res.data.code==1000){
                        console.log('添加成功') 
                    }
                })
            },
            content2chatList(contentList) {
                let self = this
                var arr = []
                for(let i in contentList){
                    var obj = {}
                    obj.id = contentList[i].id
                    obj.date = contentList[i].createDateName
                    obj.data = contentList[i].content
                    obj.headImg = contentList[i].userImg
                    obj.from = contentList[i].userName
                    obj.to = contentList[i].serviceName
                    arr.push(obj)
                }
                this.chatList = arr
                self.$nextTick(()=> {
                    let aa = self.$refs.chatBoxDemo.offsetHeight
                    console.log(aa)
                    self.$refs.chatBoxScroll.scrollTop = aa;
                })
            },
            IMlogin() { 
                let self = this;
                console.log(123)
                var options = {
                        apiUrl: this.$WebIM.config.apiURL,
                        user: this.phone,
                        // user: "18062763119",
                        pwd: "123456",
                        appKey: this.$WebIM.config.appkey,
                        success: function (token) {
                            // console.log('登录成功'+token)
                            // var token = token.access_token;
                            // this.$WebIM.utils.setCookie('webim_' + encryptUsername, token, 1);
                            // self.$imConn.setPresence();//设置在线状态
                            // self.getHaoYouList()
                        },
                        error: function(){
                        }
                    };
                this.$imConn.open(options);
            },
            choose(id){
                this.messageList=[]
                this.loadingText="正在加载",
                this.pageNumber=0
                if(id=='tb_user_entity'){
                   this.now="tb_user_entity"
                   this.loadMore()
                }else{
                    this.now=""
                    this.loadMore()
                }
            },
            loadMore(){
                this.busy =true;
                this.pageNumber++;
                  if(this.now=="tb_user_entity"){
                    this.getList()
                  }else{
                    this.getfans()
                  }
            },
        }
    }
</script>

<style lang="less" scoped>
     .group{
       position: absolute;
        top:44px;
        left:0;
        right:0;
        bottom: 0;
        overflow:auto;
        background: #f2f3f6;
     }
     .scroll-box{
     }
    .chat-warp{
        height: 100%;
        box-sizing: border-box;
        // padding-top: 20rem/75;
        position: relative;
        background: rgb(243,245,249);
        padding-top: 12rem/75;
        overflow: hidden;
        .goods-warp{
            height: 150rem/75;
            display: flex;
            background: #fff;
            padding: 24rem/75;
            img.left{
                width: 100rem/75;
                height: 100rem/75;
                margin-right: 20rem/75;
            }
            .name-box{
                font-size: 28rem/75;
                color: #000;
            }
            .section-line{
                font-size: 20rem/75;
                color: #bbb;
                margin-top: 8rem/75;
            }
            .supplement{
                font-size: 20rem/75;
                color: #bbb;
                margin-top: 8rem/75;
            }
        }
        .chatBox-kuang{
            width: 100%;
            height: calc(100% - 162rem/75);
            //background: #fff;
            text-align: left;
            position: absolute;
            top: 162rem/75;
            left: 0;
            .chatBox-content{
                height: calc(100% - 94rem/75);
                overflow-y: scroll;
                .chatBox-content-demo{
                    width: 100%;
                    //overflow-y: scroll;
                    .clearfloat{
                        .author-name{
                            text-align: center;
                            margin: 15px 0 5px 0;
                            color: #888;
                        } 
                        .right{
                            float: right;
                            text-align: right;
                            .chat-avatars {
                                margin-left: 10px;
                            } 
                            .chat-message{
                                background: #8c85e6;
                                color: #fff;
                                text-align: left;
                                min-height: 36px;
                                margin-left: 10px;
                            }
                            .chat-message:before {
                                position: absolute;
                                content: "";
                                top: 8px;
                                right: -6px;
                                border-top: 10px solid transparent;
                                border-bottom: 10px solid transparent;
                                border-left: 10px solid #8c85e6;
                            }
                        }
                        .left{
                            text-align: left;
                            .chat-avatars {
                                margin-right: 10px;
                            } 
                            .chat-message{
                                background: #D9D9D9;
                                min-height: 36px;
                            }
                            .chat-message:before {
                                position: absolute;
                                content: "";
                                top: 8px;
                                left: -6px;
                                border-top: 10px solid transparent;
                                border-bottom: 10px solid transparent;
                                border-right: 10px solid #D9D9D9;
                            }
                            .chat-avatars{
                              float: left;
                            }
                        }
                        .chat-message {
                            max-width: 252px;
                            text-align: left;
                            padding: 8px 12px;
                            border-radius: 6px;
                            word-wrap: break-word;
                            display: inline-block;
                            position: relative;
                        }
                        .chat-avatars {
                            display: inline-block;
                            width: 30px;
                            height: 30px;
                            border-radius: 50%;
                            background: #eee;
                            vertical-align: top;
                            overflow: hidden;
                            img{
                                width: 30px;
                                height: 30px;
                            }
                        }
                    }
                }
            }
            .chatBox-send {
                width: 100%;
                height: 94rem/75;
                background: #fff;
                border-top: 1px #D0D0D0 solid;
                position: absolute;
                bottom: 0;
                left: 0;
                display: flex;
                box-sizing: border-box;
                input{
                    padding-left: 6rem/75;
                    width: 550rem/75;
                    border: none;
                    font-size: 28rem/75;
                }
                div{
                    height: 94rem/75;
                    line-height: 94rem/75;
                    width: 200rem/75;
                    background: rgb(255,74,94);
                    text-align: center;
                    color: #fff;
                    font-size: 28rem/75;
                }
            }
        }
    }

    .clearfloat {
        zoom: 1;
        margin: 10px 10px;
    }
    .clearfloat:after {
        display: block;
        clear: both;
        content: "";
        visibility: hidden;
        height: 0;
    }



</style>

<style>
    /*.chat-warp .vux-tab .vux-tab-item.vux-tab-selected {
        color: #feba4e;
    }

    .chat-warp .vux-tab .vux-tab-item {
        color: #333333;
    }*/
</style>
